﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Xml.Linq;
using SilverQuery;
using SilverPortal.Util;
using System.Reflection;

namespace SilverPortal
{
	/// <summary>
	/// Object representation of the portal xml configuration.
	/// </summary>
	public class PortalConfig
	{
		public PortalConfig(XDocument configXml)
		{
			this.Settings = new Dictionary<string,string>();
			this.Tabs = new List<TabConfig>();

			var settings = configXml.Element("settings");
			if (settings != null)
			{
				LoadSettings(settings.Descendants("setting"), this.Settings);
			}

			foreach (XElement tabElem in configXml.Descendants("tab"))
			{
				var tab = new TabConfig(tabElem.Attribute("title").Value);
				tab.NumColumns = XmlHelper.GetIntAttribute(tabElem, "columns", 2);
				
				this.Tabs.Add(tab);

				foreach (XElement moduleElem in tabElem.Descendants("module"))
				{
					var module = new ModuleConfig(moduleElem.Attribute("title").Value);

					module.TypeName = moduleElem.Attribute("type").Value;				
					module.Css = moduleElem.Attribute("css").Value;

					LoadSettings(moduleElem.Descendants("setting"), module.Settings);
					tab.Modules.Add(module);
				}
			}
		}

		private void LoadSettings(IEnumerable<XElement> elements, Dictionary<string, string> settings)
		{
			foreach (XElement setting in elements)
			{
				settings[setting.Attribute("name").Value] = setting.Attribute("value").Value;
			}
		}

		public Dictionary<string, string> Settings { get; private set; }
		public IList<TabConfig> Tabs { get; private set; }
	}

	public class TabConfig
	{
		public TabConfig(string title)
		{
			this.Title = title;
			this.Modules = new List<ModuleConfig>();
		}

		public string Title { get; private set; }
		public int NumColumns { get; internal set; }
		public IList<ModuleConfig> Modules { get; private set; }
	}

	public class ModuleConfig
	{
		public ModuleConfig(string title)
		{
			this.Title = title;
			this.Settings = new Dictionary<string, string>();
		}

		public string Title { get; private set; }
		public string TypeName { get; set; }
		public Dictionary<string, string> Settings { get; private set; }
		public string Css { get; set; }
	}
}